Coverage Report

Created: 2026-11-19 22:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
D:\a\cssh-rs\cssh-rs\cssh-rs-protocol\src\v1\codec.rs
Line
Count
Source
1
//! Length-prefixed CBOR framing for the v1 control channel.
2
//!
3
//! Each frame on the wire is:
4
//!
5
//! ```text
6
//! [u32 length, big-endian] [CBOR body of length bytes]
7
//! ```
8
//!
9
//! The length counts only the CBOR body, not the 4-byte prefix. The maximum
10
//! body size is a per-call parameter, not part of the wire format, so peers
11
//! enforce a negotiated limit (default
12
//! [`crate::v1::limits::DEFAULT_MAX_FRAME_LEN`]).
13
//!
14
//! Forward compatibility rides on the length prefix. `#[serde(other)]` absorbs
15
//! an unknown *unit* variant, but cannot fold an unknown *data-carrying*
16
//! message into a unit catch-all; for those, [`decode_frames`] drops the whole
17
//! (length-delimited) frame and counts the skip, so an unknown message never
18
//! crashes the stream. A length prefix over the enforced limit is the one
19
//! unrecoverable case: the boundary can no longer be trusted, so decoding fails
20
//! hard and the caller tears the connection down.
21
22
use std::io::{self, Write};
23
24
use serde::de::DeserializeOwned;
25
use serde::Serialize;
26
27
/// Number of bytes in a frame's big-endian `u32` length prefix.
28
const LENGTH_PREFIX_LEN: usize = 4;
29
30
/// Error produced while encoding or decoding length-prefixed CBOR frames.
31
#[derive(Debug, thiserror::Error)]
32
pub enum FramingError {
33
    /// The CBOR body could not be encoded.
34
    #[error("failed to encode CBOR frame body")]
35
    Encode(#[from] ciborium::ser::Error<std::io::Error>),
36
    /// A frame body exceeds the enforced limit - the declared length on decode
37
    /// (unrecoverable, so the caller tears the connection down), or the limit
38
    /// on encode.
39
    #[error("frame length {0} exceeds the maximum frame size")]
40
    FrameTooLarge(u32),
41
}
42
43
/// Result of decoding a buffer that may hold several frames.
44
#[derive(Debug, Clone, PartialEq)]
45
pub struct DecodedFrames<T> {
46
    /// Successfully decoded messages, in wire order.
47
    pub messages: Vec<T>,
48
    /// Count of complete but undecodable frames that were skipped - an
49
    /// unknown data-carrying message from a newer minor version, or a corrupt
50
    /// body. Skipping is safe because each frame is length-delimited.
51
    pub skipped: usize,
52
    /// Unconsumed trailing bytes (a partial final frame) to prepend to the
53
    /// next read; reuses the input buffer's allocation.
54
    pub remainder: Vec<u8>,
55
}
56
57
/// A `Write` sink that buffers at most `limit` bytes.
58
///
59
/// Lets [`encode_frame`] bound its allocation so a pathologically large
60
/// message fails fast instead of serializing far past the limit before the
61
/// size check.
62
struct LimitedWriter {
63
    buffer: Vec<u8>,
64
    limit: usize,
65
    overflowed: bool,
66
}
67
68
impl Write for LimitedWriter {
69
1.04k
    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
70
1.04k
        if self.buffer.len() + data.len() > self.limit {
71
1
            self.overflowed = true;
72
1
            return Err(io::Error::new(
73
1
                io::ErrorKind::WriteZero,
74
1
                "frame body exceeds the maximum frame size",
75
1
            ));
76
1.04k
        }
77
1.04k
        self.buffer.extend_from_slice(data);
78
1.04k
        return Ok(data.len());
79
1.04k
    }
80
81
0
    fn flush(&mut self) -> io::Result<()> {
82
0
        return Ok(());
83
0
    }
84
}
85
86
/// Encode a message into a single length-prefixed CBOR frame.
87
///
88
/// # Arguments
89
/// * `message` - The value to serialize into a frame.
90
/// * `max_frame_len` - Largest body, in bytes, to emit (the negotiated send
91
///   limit).
92
///
93
/// # Returns
94
/// The framed bytes: a big-endian `u32` body length followed by the CBOR
95
/// body.
96
///
97
/// # Errors
98
/// Returns [`FramingError::FrameTooLarge`] if the serialized body would exceed
99
/// `max_frame_len`, or [`FramingError::Encode`] for any other serialization
100
/// failure.
101
51
pub fn encode_frame<T: Serialize>(
102
51
    message: &T,
103
51
    max_frame_len: u32,
104
51
) -> Result<Vec<u8>, FramingError> {
105
51
    let mut writer = LimitedWriter {
106
51
        buffer: Vec::new(),
107
51
        limit: max_frame_len as usize,
108
51
        overflowed: false,
109
51
    };
110
51
    if let Err(
error1
) = ciborium::ser::into_writer(message, &mut writer) {
111
1
        if writer.overflowed {
112
1
            return Err(FramingError::FrameTooLarge(max_frame_len));
113
0
        }
114
0
        return Err(FramingError::Encode(error));
115
50
    }
116
50
    let body = writer.buffer;
117
50
    let mut frame = Vec::with_capacity(LENGTH_PREFIX_LEN + body.len());
118
50
    frame.extend_from_slice(&(body.len() as u32).to_be_bytes());
119
50
    frame.extend_from_slice(&body);
120
50
    return Ok(frame);
121
51
}
122
123
/// Decode every complete frame in `buffer`, consuming it.
124
///
125
/// Frames whose body does not deserialize into `T` (an unknown message kind
126
/// or a corrupt body) are skipped and counted rather than aborting the batch,
127
/// since the length prefix delimits each body exactly.
128
///
129
/// # Arguments
130
/// * `buffer` - Bytes read from the control channel, possibly ending in a
131
///   partial frame. Its allocation is reused for the returned remainder.
132
/// * `max_frame_len` - Largest body, in bytes, to accept (this endpoint's
133
///   receive ceiling).
134
///
135
/// # Returns
136
/// A [`DecodedFrames`] holding the decoded messages, the count of skipped
137
/// frames, and any unconsumed trailing bytes.
138
///
139
/// # Errors
140
/// Returns [`FramingError::FrameTooLarge`] if a frame's declared length
141
/// exceeds `max_frame_len`, which leaves the stream unresynchronizable.
142
29
pub fn decode_frames<T: DeserializeOwned>(
143
29
    mut buffer: Vec<u8>,
144
29
    max_frame_len: u32,
145
29
) -> Result<DecodedFrames<T>, FramingError> {
146
29
    let mut messages = Vec::new();
147
29
    let mut skipped = 0;
148
29
    let mut pos = 0;
149
60
    while pos + LENGTH_PREFIX_LEN <= buffer.len() {
150
33
        let len = u32::from_be_bytes([
151
33
            buffer[pos],
152
33
            buffer[pos + 1],
153
33
            buffer[pos + 2],
154
33
            buffer[pos + 3],
155
33
        ]);
156
33
        if len > max_frame_len {
157
1
            return Err(FramingError::FrameTooLarge(len));
158
32
        }
159
32
        let body_start = pos + LENGTH_PREFIX_LEN;
160
32
        let body_end = body_start + len as usize;
161
32
        if body_end > buffer.len() {
162
            // The trailing frame is incomplete; hand it back as remainder.
163
1
            break;
164
31
        }
165
31
        match ciborium::de::from_reader(&buffer[body_start..body_end]) {
166
29
            Ok(message) => messages.push(message),
167
2
            Err(_) => skipped += 1,
168
        }
169
31
        pos = body_end;
170
    }
171
28
    buffer.drain(..pos);
172
28
    return Ok(DecodedFrames {
173
28
        messages,
174
28
        skipped,
175
28
        remainder: buffer,
176
28
    });
177
29
}
178
179
#[cfg(test)]
180
#[path = "../tests/v1/test_codec.rs"]
181
mod tests;